<script setup lang="ts">
import {nextTick, ref, watch} from 'vue'

const emit = defineEmits(['actionDone'])

const messageBoxShow = ref(false)
const title = ref('')

const socket = ref<WebSocket>()
const receiveMessages = ref<ReceiveMessage[]>([])

watch(messageBoxShow, (newValue) => {
  if (newValue) {
    socket.value = new WebSocket('ws://127.0.0.1:10000/ws/manageServer')

    socket.value?.addEventListener('open', () => {
      console.log('message box socket 连接已建立')
    })
    socket.value.addEventListener('close', () => {
      emit('actionDone')
      console.log('message box socket 连接已关闭')
    })

    receiveMessages.value = []
    socket.value?.addEventListener('message', (event: any) => {
      const receiveData: ReceiveMessage = JSON.parse(event.data)
      console.log(receiveData)
      receiveMessages.value.push(receiveData)
      if (receiveData.type === 'errorMessage') {
        // 出现错误就关闭连接
        socket.value?.close()
      }
    })
  } else {
    socket.value?.close()
  }
})

function openMessageBox(action: ActionForSendMessage, id: number) {
  console.log(action + ' ' + id)
  messageBoxShow.value = true
  title.value = action

  nextTick(() => {
    socket.value?.addEventListener('open', () => {
      const sendData: SocketSendData<number> = {
        action,
        data: id,
      }
      socket.value?.send(JSON.stringify(sendData))
    })
  })
}

defineExpose({openMessageBox})
</script>

<template>
  <el-dialog v-model="messageBoxShow"
             :title="title"
             width="500"
             align-center
  >
    <div class="receiveMessage">
      <p v-for="(message, index) in receiveMessages" :key="index" :class="message.type">
        {{ message.msg }}
      </p>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="messageBoxShow = false">Close</el-button>
        <!--<el-button type="primary" @click="receiveMessageDialog = false">-->
        <!--  Confirm-->
        <!--</el-button>-->
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="stylus">
.receiveMessage
  border: 1px solid #ccc
  text-align: center;
  font-size 18px

  .successMessage
    color green

  .errorMessage
    color red

  .infoMessage
    color #028e8e
</style>